package cz.proks.schoolpupilbook.gwt.widget.common;

import java.util.Iterator;
import java.util.LinkedList;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class Errors extends Composite {

	@UiTemplate("Errors.ui.xml")
	interface ErrorsUiBinder extends UiBinder<Widget, Errors> {
	}
	
	private static ErrorsUiBinder uiBinder = GWT.create(ErrorsUiBinder.class);
	
	@UiField VerticalPanel errors;

	public Errors() {
		initWidget(uiBinder.createAndBindUi(this));
		setVisible(false);
	}	

	private void addError(String error) {
		if (error != null && !error.isEmpty())
		errors.add(new Label(error));
	}
	
	private void addErrors(LinkedList<String> errorList) {
		if (errorList != null) {
			for(String error : errorList) {
				addError(error);
			}
		}
	}
	
	public void setErrors(LinkedList<String> errorList) {
		errors.clear();
		
		if (errorList == null || errorList.isEmpty())
			setVisible(false);
		else {
			setVisible(true);
			addErrors(errorList);	
		}		
	}
	
	public LinkedList<String> getErrors() {
		LinkedList<String> errorList = new LinkedList<String>();		
		Iterator<Widget> iterator = errors.iterator();
		
		while (iterator.hasNext()) {
			Widget widget = (Widget) iterator.next();
			
			if (widget instanceof HasText)
				errorList.add(((HasText)widget).getText());			
		}
		
		return errorList;
	}	
}
